package com.ck.company.controller;

import com.ck.company.service.CpPictureService;
import com.ck.constant.FileConstant;
import com.ck.constant.RequestConstant;
import com.ck.constant.ResponseConstant;
import com.ck.exception.ControllerException;
import com.ck.model.common.Picture;
import com.ck.model.common.User;
import com.ck.model.common.page.PageInfo;
import com.ck.model.common.sys.JsonResponse;
import com.ck.model.company.vo.CpPictureListVO;
import com.google.common.collect.Lists;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 图片Controller
 *
 * @author dxy
 * @date 2018/7/3 18:03
 */
@Controller
@RequestMapping("/cpPicture")
public class CpPictureController {
	private static Logger logger = LoggerFactory.getLogger(CpPictureController.class);
	@Autowired
	private CpPictureService cpPictureService;

	/**
	 * 上传图片
	 */
	@ResponseBody
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public Object uploadPicture(@RequestParam("files") MultipartFile files, HttpServletRequest request) {
		try {
			//获取文件全名称
			String originalFilename = files.getOriginalFilename();
			if (StringUtils.isBlank(originalFilename)) {
				return new JsonResponse(ResponseConstant.CODE_FAIL, "文件名不能为空");
			}
			//去掉后缀，获取纯文件名
			String extension = FilenameUtils.getExtension(originalFilename);
			//校验文件后缀是否是图片
			if (!FileConstant.IMAGE_SUFFIX_LIST.contains(extension)) {
				return new JsonResponse(ResponseConstant.CODE_FAIL, "文件格式不正确，请上传图片文件");
			}
			String fileName = originalFilename.replaceAll("." + extension, "").trim();
			if (StringUtils.isBlank(fileName)) {
				return new JsonResponse(ResponseConstant.CODE_FAIL, "文件名不能为空");
			}
			List msgList = Lists.newArrayList();
			Map<String, Object> fileMsgMap = cpPictureService.savePicture(files, request);
			msgList.add(fileMsgMap);
			return msgList;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("CpPictureController uploadPicture 上传图片失败：" + e.getMessage());
			return e;
		}
	}

	/**
	 * 重命名
	 */
	@ResponseBody
	@RequestMapping("/rename")
	public Object renamePicture(Long pictureId, String picutreNewName, HttpServletRequest request) {
		//验证图片ID不能为空
		if (pictureId == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "图片ID名称不能为空, 请联系管理员");
		}
		//验证图片名不能为空
		if (StringUtils.isBlank(picutreNewName)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "图片名称不能为空");
		}
		try {
			//获取用户的company_code
			User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
			String companyCode = loginUser.getCompanyCode();
			//验证文件名不能重复
			Picture picture = cpPictureService.getPictureByName(companyCode, picutreNewName);
			if (picture != null) {
				return new JsonResponse(ResponseConstant.CODE_FAIL, "文件名已存在");
			}
			cpPictureService.renamePicture(pictureId, picutreNewName, request);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("CpPictureController renamePicture 重命名图片失败：" + e.getMessage());
			return new ControllerException("重命名失败： " + e.getMessage());
		}
		return "";
	}

	/**
	 * 图片列表
	 */
	@RequestMapping("/list")
	public String listPicture(String pictureName, Long pictureGroupId, String currentGroupName, Integer pageNum,
							  Integer pageSize, Model model, HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
		String companyCode = user.getCompanyCode();
		PageInfo<CpPictureListVO> pageInfo = cpPictureService.list(companyCode, pictureName, pictureGroupId, pageNum, pageSize);
		model.addAttribute("pictureName", pictureName);
		model.addAttribute("pictureGroupId", pictureGroupId);
		model.addAttribute("currentGroupName", currentGroupName);
		model.addAttribute("pictureList", pageInfo.getList());
		model.addAttribute("pageNum", pageInfo.getPageNum());
		model.addAttribute("pageSize", pageInfo.getPageSize());
		model.addAttribute("total", pageInfo.getTotal());
		return "cp/cp_picture_list";
	}

	/**
	 * 更新图片分组ID
	 */
	@ResponseBody
	@RequestMapping(value = "/updatePictureGroupId")
	public Object updatePictureGroupId(Long pictureGroupId, Long pictureId) {
		if (pictureId == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "图片ID不能为空,请联系管理员");
		}
		try {
			cpPictureService.updatePictureGroupId(pictureGroupId, pictureId);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("CpPictureController updatePictureGroupId 更新图片分组ID失败：" + e.getMessage());
			return e;
		}
		return "";
	}

	/**
	 * 删除图片
	 */
	@ResponseBody
	@RequestMapping(value = "/delete")
	public Object deletePicutre(Long pictureId, HttpServletRequest request) {
		if (pictureId == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "图片ID不能为空，请联系管理员");
		}
		try {
			cpPictureService.deletePictureById(pictureId, request);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("CpPictureController deletePicutre 删除图片失败：" + e.getMessage());
			return e;
		}
		return "";
	}

}
